<script>
import { ref, computed, onMounted } from 'vue'
import request from '@/utils/request.js'
import { ElMessage } from 'element-plus'

export default {
  name: 'Users',
  setup() {
    const users = ref([])
    const searchForm = ref({
      username: null,
      role: null,
      status: null
    })
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    const getUsers = async (params = {}) => {
      try {
        const response = await request.get('/user/page', { params: { ...params, page: currentPage.value, size: pageSize.value } })
        if (response.code === 1) {
          users.value = response.data.list
          total.value = response.data.total
        } else {
          console.error(response.msg || '获取用户列表失败')
        }
      } catch (error) {
        console.error('服务异常')
      }
    }

    const filteredUsers = computed(() => {
      return users.value.filter(user => {
        if (searchForm.value.username && !user.username.includes(searchForm.value.username)) {
          return false
        }
        if (searchForm.value.role !== null && user.role !== searchForm.value.role) {
          return false
        }
        if (searchForm.value.status !== null && user.status !== searchForm.value.status) {
          return false
        }
        return true
      })
    })

    const onSearch = () => {
      getUsers({ ...searchForm.value })
    }

    const changeRole = async (user) => {
      try {
        const newRole = user.role === 1 ? 2 : 1
        const response = await request.put('/user', { id: user.id, role: newRole })
        if (response.code === 1) {
          ElMessage.success('角色更新成功')
          getUsers()
        } else {
          ElMessage.error(response.msg || '角色更新失败')
        }
      } catch (error) {
        ElMessage.error('服务异常')
      }
    }

    const handleSizeChange = (newSize) => {
      pageSize.value = newSize
      getUsers()
    }

    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage
      getUsers()
    }

    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }

    onMounted(() => {
      getUsers()
    })

    return {
      users,
      searchForm,
      filteredUsers,
      onSearch,
      changeRole,
      currentPage,
      pageSize,
      total,
      handleSizeChange,
      handleCurrentChange,
      formatDate
    }
  }
}
</script>

<template>
  <div class="users-container">
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="用户名">
        <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="身份">
        <el-radio-group v-model="searchForm.role">
          <el-radio :label="1">用户</el-radio>
          <el-radio :label="2">管理员</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="searchForm.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="2">冻结中</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="filteredUsers" style="width: 100%">
      <el-table-column prop="username" label="用户名" width="180"></el-table-column>
      <el-table-column label="角色" width="180">
        <template #default="scope">
          {{ scope.row.role === 1 ? '用户' : '管理员' }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="scope">
          {{ scope.row.status === 1 ? '正常' : '冻结中' }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="最后更新时间">
        <template #default="scope">
          {{ formatDate(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="text" @click="changeRole(scope.row)">
            {{ scope.row.role === 1 ? '设为管理员' : '设为用户' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    />
  </div>
</template>

<style scoped>
.users-container {
  padding: 20px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.example-pagination-block + .example-pagination-block {
  margin-top: 10px;
}

.example-pagination-block .example-demonstration {
  margin-bottom: 16px;
}
</style>